package com.ozo.cloud.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ozo.cloud.common.base.model.BaseBatchDTO;
import com.ozo.cloud.common.base.model.BasePage;
import com.ozo.cloud.common.base.model.PageResult;
import com.ozo.cloud.common.database.util.SortUtils;
import com.ozo.cloud.system.entity.SysLoginLog;
import com.ozo.cloud.system.mapper.SysLoginLogMapper;
import com.ozo.cloud.system.pojo.dto.SysLoginLogQueryDTO;
import com.ozo.cloud.system.pojo.vo.SysLoginLogVO;
import com.ozo.cloud.system.service.ISysLoginLogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 登录日志 服务实现类
 *
 * @author qiangesoft
 * @version 1.0
 * @date 2024-11-20 15:14:30
 */
@Service
public class SysLoginLogServiceImpl extends ServiceImpl<SysLoginLogMapper, SysLoginLog> implements ISysLoginLogService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void remove(BaseBatchDTO<Long> batchDTO) {
        baseMapper.deleteBatchIds(batchDTO.getIdList());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void clear() {
        baseMapper.delete(new QueryWrapper<SysLoginLog>().eq("1", "1"));
    }

    @Override
    public PageResult<SysLoginLogVO> page(BasePage basePage, SysLoginLogQueryDTO queryDTO) {
        Integer pageNum = basePage.getPageNum();
        Integer pageSize = basePage.getPageSize();

        QueryWrapper<SysLoginLog> queryWrapper = new QueryWrapper<>();
        // 排序
        String order = basePage.getOrder();
        if (StrUtil.isBlank(order)) {
            queryWrapper.lambda().orderByDesc(SysLoginLog::getId);
        } else {
            SortUtils.setSortCondition(queryWrapper, basePage.getProp(), order);
        }
        // 条件
        queryWrapper.lambda()
                .like(StrUtil.isNotBlank(queryDTO.getUsername()), SysLoginLog::getUsername, queryDTO.getUsername());
        Page<SysLoginLog> page = baseMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);

        PageResult<SysLoginLogVO> pageResult = new PageResult<>();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setPage(page.getPages());
        pageResult.setTotal(page.getTotal());
        List<SysLoginLog> recordList = page.getRecords();
        List<SysLoginLogVO> recordVOList = BeanUtil.copyToList(recordList, SysLoginLogVO.class);
        pageResult.setResults(recordVOList);
        return pageResult;
    }

}
